package com.yunhe.marketing.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.github.stuxuhai.jpinyin.PinyinException;
import com.yunhe.marketing.model.EnterpriseUpload;
import com.yunhe.marketing.model.EnterpriseUploadAQC;
import com.yunhe.marketing.service.IDemandRepositoryService;
import com.yunhe.marketing.util.EnterpriseUploadAQCUtil;
import com.yunhe.marketing.util.EnterpriseUploadUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: DongWenYu
 * @Date: 2021/3/25 14:28
 */
public class AQCUploadDataListener extends AnalysisEventListener<EnterpriseUploadAQC> {

    private static final Logger logger = LoggerFactory.getLogger(AQCUploadDataListener.class);

    /**
     * 实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 50;
    List<EnterpriseUploadAQC> list = new ArrayList<EnterpriseUploadAQC>();
    /**
     * 同一个excel表中可能存在相同的数据。
     */
    List<EnterpriseUploadAQC> removeList = new ArrayList<EnterpriseUploadAQC>();
    private IDemandRepositoryService demandRepositoryService = null;
    private String fileName  = null;

    /**
     * 如果使用了spring,请使用这个构造方法。每次创建Listener的时候需要把spring管理的类传进来
     * @param demandRepositoryService
     * @return
     * @create 2021/2/23 11:24
     */
    public AQCUploadDataListener(IDemandRepositoryService demandRepositoryService , String fileName) {
        this.demandRepositoryService = demandRepositoryService;
        this.fileName = fileName;
    }

    @Override
    public void invoke(EnterpriseUploadAQC data, AnalysisContext context) {
        logger.debug("解析到一条数据:{}", JSON.toJSONString(data));
        try {
            if (!EnterpriseUploadAQCUtil.isEmpty(data)) {
                try {
                    EnterpriseUploadAQCUtil.convertToNull(data);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                for (EnterpriseUploadAQC enterpriseUploadAQC : list){
                    if (data.equals(enterpriseUploadAQC)){
                        EnterpriseUploadAQCUtil.update(data,enterpriseUploadAQC);
                        removeList.add(enterpriseUploadAQC);
                    }
                }
                list.add(data);
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (list.size() >= BATCH_COUNT) {
            try {
                removeSameData(list,removeList);
                saveData();
            } catch (PinyinException e) {
                e.printStackTrace();
            }
            // 存储完成清理 list
            list.clear();
        }

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        try {
            removeSameData(list,removeList);
            saveData();
        } catch (PinyinException e) {
            e.printStackTrace();
        }
        logger.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() throws PinyinException {
        logger.info("文件名:{},{}条数据，开始存储数据库！", fileName,list.size());
        demandRepositoryService.uploadAQC(list);
    }

    /**
     * 移除相同数据
     */
    private void removeSameData( List<EnterpriseUploadAQC> list ,  List<EnterpriseUploadAQC> removeList) throws PinyinException {
        for (EnterpriseUploadAQC enterpriseUploadAQC : removeList){
            list.remove(enterpriseUploadAQC);
        }
        removeList.clear();
    }
}
